﻿using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Xml;
using System.Xml.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Formatting = Newtonsoft.Json.Formatting;


namespace ManufacturerLicenseTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "server=localhost; userid=root; password=123456; port=3306; database=lts; sslmode=Required;";
            //string connectionString = "server=rm-wz9ou0b43d2pppjh4.mysql.rds.aliyuncs.com; userid=root; password=mannings2020!; port=3306; database=lts; sslmode=none; Allow Zero Datetime=True; Convert Zero Datetime=True";
            // 配置数据库连接
            var options = new DbContextOptionsBuilder<TestDbContext>()
            .UseMySql(connectionString, ServerVersion.AutoDetect(connectionString))
            .Options;

            using var dbContext = new TestDbContext(options);
            var loggerFactory = LoggerFactory.Create(builder =>
            {
                builder.AddSimpleConsole(options =>
                {
                    options.SingleLine = true;
                    options.TimestampFormat = "HH:mm:ss ";
                });
            });
            var logger = loggerFactory.CreateLogger<Manufacturer>();
            var attachmentService = new MockAttachmentService();
            var sharedService = new MockSharedService();

            // 创建服务实例
            var service = new ManufacturerService(dbContext, logger, attachmentService)
            {
                _sharedService = sharedService
            };

            // 创建测试的Manufacturer对象
            var manufacturer = dbContext.Manufacturers
            .Include(m => m.ManufacturerLicenses)
            .ThenInclude(l => l.Attachments)
            .FirstOrDefault(m => m.Name == "test1");

            if (manufacturer == null)
            {
                Console.WriteLine("没有找到对应的Manufacturer数据！");
                return;
            }

            // 调用SaveLicense方法
            Console.WriteLine("调用SaveLicense方法...");
            Console.WriteLine("========================================");
            Console.WriteLine("参数值：" + JsonConvert.SerializeObject(manufacturer, Formatting.Indented));
            service.SaveLicense(manufacturer);
            Console.WriteLine("========================================");
            Console.WriteLine("测试完成");
        }
    }

    // 测试数据库上下文
    public class TestDbContext : DbContext
    {
        public TestDbContext(DbContextOptions options) : base(options) { }
        public DbSet<Manufacturer> Manufacturers { get; set; }
        public DbSet<ManufacturerLicense> ManufacturerLicenses { get; set; }
        public DbSet<ManufacturerLicenseAttachment> ManufacturerLicenseAttachments { get; set; }
        public DbSet<LicenseType> LicenseTypes { get; set; }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // 这里配置 Manufacturer 和 ManufacturerLicense 关系
            modelBuilder.Entity<ManufacturerLicense>()
                .HasOne<Manufacturer>()
                .WithMany(m => m.ManufacturerLicenses)
                .HasForeignKey(l => l.ManufacturerId);

            // 配置 ManufacturerLicense 关联附件
            modelBuilder.Entity<ManufacturerLicense>()
                .HasMany(l => l.Attachments)
                .WithOne()
                .HasForeignKey(a => a.LicenseId);
        }
    }

    // 模拟附件服务
    public class MockAttachmentService
    {
        public List<ManufacturerLicenseAttachment> GetList(string licenseId, bool isMain)
        {
            return new List<ManufacturerLicenseAttachment>
            {
                new ManufacturerLicenseAttachment
                {
                    URL = isMain ?
                        $"https://mock.com/main_{licenseId}.jpg" :
                        $"https://mock.com/extra_{licenseId}.jpg"
                }
            };
        }
    }

    // 模拟共享服务
    public class MockSharedService
    {
        public string GetConfig(string key)
        {
            return "mock-ekp-template-id";
        }
    }

    public class Manufacturer
    {
        public string? Id { get; set; }
        public string? MId { get; set; }
        public string? Name { get; set; }
        public string? Register { get; set; }
        public string? RegisterCode { get; set; }
        public string? ResponsiblePerson { get; set; }
        public string? CreatedBy { get; set; }
        public DateTime? CreatedOn { get; set; }
        public string? LastModifiedBy { get; set; }
        public DateTime? LastModifiedOn { get; set; }
        public int? LicenseNum { get; set; }
        public int? ProductType { get; set; }
        public List<ManufacturerLicense> ManufacturerLicenses { get; set; }
    }

    public class ManufacturerLicense
    {
        public string Id { get; set; } = Guid.NewGuid().ToString();
        public string? ManufacturerId { get; set; }
        public string? Type { get; set; }
        public DateTime? ValidFromDate { get; set; }
        public DateTime? ValidToDate { get; set; }
        public string? LId { get; set; }
        public bool IsPublish { get; set; }
        public int? OperationType { get; set; }
        public string? CreatedBy { get; set; }
        public string RefFlowId { get; set; } = Guid.NewGuid().ToString();
        public List<ManufacturerLicenseAttachment> Attachments { get; set; } = new List<ManufacturerLicenseAttachment>();
    }

    public class ManufacturerLicenseAttachment
    {
        public string? Id { get; set; }
        public string? LicenseId { get; set; }
        public bool IsMain { get; set; }
        public string? URL { get; set; }
    }

    public class LicenseType
    {
        [Key]
        public string TypeId { get; set; }
        public string TypeName { get; set; }
        public string Module { get; set; }
    }

    public class Comparator
    {
        public bool DifferenceComparison<T>(List<T> list1, List<T> list2) => true;
        public bool DifferenceEntityComparison<T>(T entity1, T entity2) => true;
    }

    public class ManufacturerService
    {
        public TestDbContext _dbContext;
        private readonly ILogger<Manufacturer> _logger;
        private Comparator _comparator = new Comparator();
        private MockAttachmentService _attachmentService;
        public MockSharedService _sharedService;

        public ManufacturerService(TestDbContext dbContext, ILogger<Manufacturer> logger, MockAttachmentService attachmentService)
        {
            _dbContext = dbContext;
            _logger = logger;
            _attachmentService = attachmentService;
        }

        public void SaveLicense(Manufacturer manufacturer)
        {
            Console.WriteLine("开始执行SaveLicense方法");
            var licenses = manufacturer.ManufacturerLicenses;
            var id = manufacturer.Id;
            var userId = manufacturer.LastModifiedBy;

            var exists = _dbContext.ManufacturerLicenses
                .Where(s => s.ManufacturerId == id && s.IsPublish == true)
                .OrderBy(s => s.Id)
                .ToList();

            var licensesCompare = licenses.OrderBy(l => l.Id).ToList();

            // 输出信息————————————————————————————————————————————
            Console.WriteLine("exists 的数量: {0}", exists.Count);
            foreach (var item in exists)
            {
                Console.WriteLine("exists - Id: {0}, ManufacturerId: {1}, IsPublish: {2}", item.Id, item.ManufacturerId, item.IsPublish);
            }

            Console.WriteLine("licensesCompare 的数量: {0}", licensesCompare.Count);
            foreach (var item in licensesCompare)
            {
                Console.WriteLine("licensesCompare - Id: {0}", item.Id);
            }

            Console.WriteLine("检查能否启动表单：");
            //————————————————————————————————————————
            if (_comparator.DifferenceComparison(exists, licensesCompare))
            {
                // 发起流程
                var currentTbId = "fd_3c7343ed25a0e8";//控件
                var historyTbId = "fd_3c7344bbcb4a6c";//控件

                var formValues = "{\"fd_3c73440309699e\":\"" + manufacturer.Name + "\", \"fd_3c734404052200\":\"" + manufacturer.MId + "\",";

                // 历史证照数据
                var tbHistoryValue1 = $"\"{historyTbId}.fd_3c7344e5124b46\":[";
                var tbHistoryValue2 = $"\"{historyTbId}.fd_3c749202cd5272\":[";
                var tbHistoryValue3 = $"\"{historyTbId}.fd_3c749204297b04\":[";
                var tbHistoryValue4 = $"\"{historyTbId}.fd_3c7344e8f4f4b6\":[";
                var tbHistoryValue5 = $"\"{historyTbId}.fd_3c7344ea331368\":[";

                if (exists != null && exists.Any())
                {
                    exists.ForEach(e =>
                    {
                        var attachmentURL = string.Empty;
                        var attachment = _attachmentService.GetList(e.Id, true).FirstOrDefault();
                        if (attachment != null)
                            attachmentURL = attachment.URL;

                        tbHistoryValue1 += "\"" + GetLicenseTypeName(e.Type, "manufacturer") + "\",";
                        tbHistoryValue2 += "\"" + ((DateTime)e.ValidFromDate).ToString("yyyy-MM-dd") + "\",";
                        tbHistoryValue3 += "\"" + ((DateTime)e.ValidToDate).ToString("yyyy-MM-dd") + "\",";
                        tbHistoryValue4 += "\"" + e.LId + "\",";
                        tbHistoryValue5 += "\"" + attachmentURL + "\",";
                    });

                    tbHistoryValue1 = tbHistoryValue1.Remove(tbHistoryValue1.LastIndexOf(","), 1) + "],";
                    tbHistoryValue2 = tbHistoryValue2.Remove(tbHistoryValue2.LastIndexOf(","), 1) + "],";
                    tbHistoryValue3 = tbHistoryValue3.Remove(tbHistoryValue3.LastIndexOf(","), 1) + "],";
                    tbHistoryValue4 = tbHistoryValue4.Remove(tbHistoryValue4.LastIndexOf(","), 1) + "],";
                    tbHistoryValue5 = tbHistoryValue5.Remove(tbHistoryValue5.LastIndexOf(","), 1) + "],";
                    formValues += tbHistoryValue1 + tbHistoryValue2 + tbHistoryValue3 + tbHistoryValue4 + tbHistoryValue5;
                }

                // 当前证照数据
                var tbValue1 = $"\"{currentTbId}.fd_3c7344a1863166\":[";
                var tbValue2 = $"\"{currentTbId}.fd_3c7491d44ed0da\":[";
                var tbValue3 = $"\"{currentTbId}.fd_3c7491d84aabe6\":[";
                var tbValue4 = $"\"{currentTbId}.fd_3c7344a53921c2\":[";
                var tbValue5 = $"\"{currentTbId}.fd_3c7344a7ced6b2\":[";
                var tbValue6 = $"\"{currentTbId}.fd_3c7344a67ef9e8\":[";

                if (licenses != null && licenses.Any())
                {
                    licenses.ForEach(license =>
                    {
                        var existLicense = exists.FirstOrDefault(l => l.Id == license.Id);
                        if (string.IsNullOrEmpty(license.Id) ||
                            _comparator.DifferenceEntityComparison(existLicense, license))
                        {
                            var opTypeString = "修改";
                            if (string.IsNullOrEmpty(license.Id))
                                opTypeString = "新增";

                            var attachmentURL = string.Empty;
                            var attachment = license.Attachments?.FirstOrDefault(l => l.IsMain == true);
                            if (attachment != null)
                                attachmentURL = attachment.URL;

                            tbValue1 += "\"" + GetLicenseTypeName(license.Type, "manufacturer") + "\",";
                            tbValue2 += "\"" + ((DateTime)license.ValidFromDate).ToString("yyyy-MM-dd") + "\",";
                            tbValue3 += "\"" + ((DateTime)license.ValidToDate).ToString("yyyy-MM-dd") + "\",";
                            tbValue4 += "\"" + license.LId + "\",";
                            tbValue5 += "\"" + opTypeString + "\",";
                            tbValue6 += "\"" + attachmentURL + "\",";
                        }
                    });

                    tbValue1 = tbValue1.Remove(tbValue1.LastIndexOf(","), 1) + "],";
                    tbValue2 = tbValue2.Remove(tbValue2.LastIndexOf(","), 1) + "],";
                    tbValue3 = tbValue3.Remove(tbValue3.LastIndexOf(","), 1) + "],";
                    tbValue4 = tbValue4.Remove(tbValue4.LastIndexOf(","), 1) + "],";
                    tbValue5 = tbValue5.Remove(tbValue5.LastIndexOf(","), 1) + "],";
                    tbValue6 = tbValue6.Remove(tbValue6.LastIndexOf(","), 1) + "]";

                    formValues += tbValue1 + tbValue2 + tbValue3 + tbValue4 + tbValue5 + tbValue6 + "}";

                    // 输出formValues
                    Console.WriteLine("====== 生成的formValues ======");
                    Console.WriteLine("检查formValues值：" + formValues);//如果有值
                    Console.WriteLine("==============================");
                }
            }
        }

        private string GetLicenseTypeName(string id, string module)
        {
            var licenseType = _dbContext.LicenseTypes
                .FirstOrDefault(l => l.TypeId == id && l.Module == module);

            return licenseType?.TypeName ?? string.Empty;
        }
    }
}